<script setup>
import { useUserStore } from "@/store";
import { onMounted, reactive, ref } from "vue";
import {
  changeUInfoService,
  changeUPwdService,
  sendEmailService,
  cancelAccountService,
} from "@/api/user";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { SUCCESS } from "@/core/constants/HttpStatus";

const router = useRouter();

const userStore = useUserStore();
const userInfo = userStore.userInfo;
// 表单引用
const changeFormRef = ref();
const ePwdFormRef = ref();
const logOutFormRef = ref();

//用户个人信息表单
const userInfoForm = reactive({
  uid: "",
  unickname: "",
  urealname: "",
  ugender: "",
  uphone: "",
  umail: "",
  uintro: "",
  uability: "",
});

//用户个人信息表单校验
/**
 * urealname:不能为空，需为汉字
 * unickname:可以为空，不为空时必须为1-10位字符
 * umail:不能为空，要符合基本邮箱写法
 * uphone:可以为空，不为空时要为合法手机号
 */
const userInfoRules = {
  uid: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  urealname: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { pattern: /[\u4e00-\u9fa5]/, message: "姓名需为中文", trigger: "blur" },
  ],
  unickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 1, max: 10, message: "用户名必须是1-10位的字符", trigger: "blur" },
  ],
  ugender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  uphone: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    {
      pattern:
        /^([0|86|17951])?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
      message: "请输入合规手机号",
      trigger: "blur",
    },
  ],
  umail: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    {
      pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
      message: "邮箱为非正常写法，请重新输入",
      trigger: "blur",
    },
  ],
};

//修改密码表单
const editPwdForm = reactive({
  oldPwd: "",
  newPwd: "",
  checkPwd: "",
  code: "",
});

//修改密码表单校验
/**
 * oldPwd:不能为空,
 * newPwd:6-15位非空字符,新密码不能与原密码相同
 * checkPwd:6-15位非空字符，需要与newPwd保持一致
 * code:6位非空数字字符
 */
const editPwdRules = {
  oldPwd: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        if (value === editPwdForm.oldPwd) {
          callback(new Error("新密码不能与原密码相同"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  checkPwd: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        //判断当前value和当前form中的newPwd是否一致
        if (value !== editPwdForm.newPwd) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { pattern: /^\d{6}$/, message: "验证码为6位非空字符", trigger: "blur" },
  ],
};

//修改密码表单
const logOutForm = reactive({
  email: "",
  pwd: "",
  code: "",
});

//获取用户个人信息
onMounted(() => {
  if (userInfo) {
    console.log(userInfo);
    userInfoForm.uid = userInfo.uid;
    userInfoForm.unickname = userInfo.unickname;
    userInfoForm.urealname = userInfo.urealname;
    userInfoForm.ugender = userInfo.ugender;
    userInfoForm.uphone = userInfo.uphone;
    userInfoForm.umail = userInfo.umail;
    userInfoForm.uintro = userInfo.uintro;
    userInfoForm.uability = userInfo.uability;
  }
});

//修改个人信息
/**
 * 保存按钮
 * 发送请求之前先对表单内容进行校验，校验成功->发送请求,校验失败->提示错误信息
 * 发送请求后，若返回信息为修改成功，调用getUserInfo往store存入用户修改后的信息，弹出成功提醒；
 *            若返回信息为请求失败原因，弹出失败原因
 */
const changeInfo = async () => {
  await changeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await changeUInfoService({
          uid: userInfoForm.uid,
          nickname: userInfoForm.unickname,
          realname: userInfoForm.urealname,
          gender: userInfoForm.ugender,
          phone: userInfoForm.uphone,
          email: userInfoForm.umail,
          intro: userInfoForm.uintro,
          ability: userInfoForm.uability,
        });
        console.log(res);
        const { code, msg } = res.data;
        if (code == SUCCESS) {
          ElMessage.success("信息保存成功！");
          userStore.fetchUserInfo();
        } else {
          throw new Error(msg);
        }
      } catch (e) {
        ElMessage.error(e.message || "信息保存失败");
      }
    } else {
      ElMessage.error("信息输入格式有误，请重新检查");
      console.log("表单校验未通过");
    }
  });
};

// 重置按钮
const reset = () => {
  // console.log(userInfoForm)
  Object.keys(userInfoForm).forEach(
    (key) => key !== "uid" && key !== "urealname"&& (userInfoForm[key] = "")
  );
};

//修改密码的验证码倒计时
const pwdData = reactive({
  show: true,
  count: "",
  timer: null,
});
// 修改密码的获取验证码按钮
const getCode = async () => {
  await sendEmailService({ email: userInfoForm.umail })
    .then((response) => {
      console.log(response.data);
      if (response.data == "succeed") {
        ElMessage.success("验证码已发送至绑定邮箱");
        let clicktime = new Date().getTime() + 60000;
        timeDown(clicktime, pwdData);
      } else {
        ElMessage.error("发送失败");
      }
    })
    .catch((e) => {
      ElMessage.error(e.message || "验证码获取失败");
    });
};
//验证码倒计时
const timeDown = (time, data) => {
  if (!data.timer) {
    data.count = Math.ceil((JSON.parse(time) - new Date().getTime()) / 1000);
    data.show = false;
    data.timer = setInterval(() => {
      if (data.count > 0) {
        data.count--;
      } else {
        data.show = true;
        clearInterval(data.timer);
        data.timer = null;
      }
    }, 1000);
  }
};

/**
 * 修改按钮
 * 发送请求之前先对表单内容进行校验，校验成功->发送请求,校验失败->提示错误信息
 * 发送请求，若返回信息为修改密码成功->弹出成功提示，将表单清空；
 *          若返回信息为请求失败原因->弹出请求失败原因
 */
const editPassowrd = async () => {
  await ePwdFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await changeUPwdService({
          uid: userInfoForm.uid,
          originalPwd: editPwdForm.oldPwd,
          newPwd: editPwdForm.checkPwd,
          code: editPwdForm.code,
        });
        console.log(res);
        const { code, msg } = res.data;
        if (code == SUCCESS) {
          ElMessage.success("密码修改成功！");
          pwdReset();
        } else {
          throw new Error(msg);
        }
      } catch (e) {
        ElMessage.error(e.message || "密码修改失败");
      }
    } else {
      ElMessage.error("输入信息有误，请重新检查");
      console.log("表单校验未通过");
    }
  });
};

// 重置按钮
const pwdReset = () => {
  Object.keys(editPwdForm).forEach((key) => (editPwdForm[key] = ""));
};
// 退出按钮
const exit = () => {
  router.push({ path: "/" });
  //移动到页面顶部
  window.scrollTo({
    top: 0,
  });
};

//注销账号表单校验
/**
 * email:不能为空,要符合基本的邮箱规则
 * pwd:6-15位非空字符，不能为空
 * code:6位非空数字字符
 */
const logOutRules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
      message: "邮箱为非正常写法，请重新输入",
      trigger: "blur",
    },
  ],
  pwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { pattern: /^\d{6}$/, message: "验证码为6位非空字符", trigger: "blur" },
  ],
};
//注销的验证码倒计时
const logoutData = reactive({
  show: true,
  count: "",
  timer: null,
});
//获取邮箱验证码（注销账号）
const sendEmail = async () => {
  try {
    if (logOutForm.email === "") {
      ElMessage.error("请输入邮箱地址");
    } else {
      const res = await sendEmailService({ email: logOutForm.email });
      console.log(res);
      if (res.data === "succeed") {
        ElMessage.success("验证码发送成功");
        let clicktime = new Date().getTime() + 60000;
        timeDown(clicktime, logoutData);
      } else {
        ElMessage.error(res.data.msg);
      }
    }
  } catch (error) {
    ElMessage.error(error.message || "验证码发送失败");
  }
};
//注销账号按钮
const confirmLogOut = async () => {
  await logOutFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await cancelAccountService({
          code: logOutForm.code,
          email: logOutForm.email,
          pwd: logOutForm.pwd,
        });
        console.log(res);
        const { code, msg } = res.data;
        if (code == SUCCESS) {
          ElMessage.success(msg || "账号注销成功");
          //退出登录
          userStore.removeData();
          router.push({ path: "/" });
        } else {
          throw new Error(msg);
        }
      } catch (error) {
        ElMessage.error(error.message || "账号注销失败");
      }
    } else {
      ElMessage.error("信息输入格式有误，请重新检查");
    }
  });
};

// 重置按钮
const logOutReset = () => {
  Object.keys(logOutForm).forEach((key) => (logOutForm[key] = ""));
};
</script>

<template>
  <!--用户个人资料-->
  <el-row class="UMwithEP-box">
    <el-tabs type="border-card">
      <el-tab-pane label="个人资料">
        <el-row class="personalFormrow">
          <el-form
            ref="changeFormRef"
            :model="userInfoForm"
            :rules="userInfoRules"
            label-width="auto"
            label-position="left"
            :inline="true"
            status-icon
          >
            <el-form-item label="账号:" prop="uid">
              <el-input disabled v-model="userInfoForm.uid"></el-input>
            </el-form-item>
            <el-form-item label="姓名:" prop="urealname">
              <el-input disabled v-model="userInfoForm.urealname"></el-input>
            </el-form-item>
            <el-form-item label="昵称:" prop="unickname">
              <el-input v-model="userInfoForm.unickname"></el-input>
            </el-form-item>

            <el-form-item label="性别:" prop="ugender">
              <el-radio-group v-model="userInfoForm.ugender">
                <el-radio label="女" value="女"></el-radio>
                <el-radio label="男" value="男"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="联系方式:" prop="uphone">
              <el-input v-model="userInfoForm.uphone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱:" prop="umail">
              <el-input v-model="userInfoForm.umail"></el-input>
            </el-form-item>
            <el-form-item label="个人简介:" class="textarea">
              <el-input
                type="textarea"
                v-model="userInfoForm.uintro"
                :rows="5"
              ></el-input>
            </el-form-item>
            <el-form-item label="能力专长:" class="textarea">
              <el-input
                type="textarea"
                v-model="userInfoForm.uability"
                :rows="8"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-row>
        <el-row class="buttonrow" type="flex" justify="center">
          <el-form-item>
            <el-button type="primary" @click="changeInfo(userInfoForm)">
              保存
            </el-button>
            <el-button type="info" @click="reset">重置</el-button>
            <el-button @click="exit">退出</el-button>
          </el-form-item>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="修改密码">
        <el-row class="updateFormrow">
          <el-form
            ref="ePwdFormRef"
            :rules="editPwdRules"
            :model="editPwdForm"
            label-width="auto"
            label-position="left"
            status-icon
          >
            <el-form-item label="原密码:" prop="oldPwd">
              <el-input
                placeholder="请输入原密码"
                v-model="editPwdForm.oldPwd"
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码:" prop="newPwd">
              <el-input
                placeholder="请输入新密码"
                v-model="editPwdForm.newPwd"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码:" prop="checkPwd">
              <el-input
                placeholder="请再次输入新密码"
                v-model="editPwdForm.checkPwd"
                show-password
              />
            </el-form-item>
            <div class="codeRow">
              <el-form-item label="验证码:" prop="code">
                <el-input
                  placeholder="请输入邮箱验证码"
                  v-model="editPwdForm.code"
                />
              </el-form-item>
              <el-button
                type="primary"
                @click="getCode"
                v-if="pwdData.show"
                plain
              >
                获取验证码
              </el-button>
              <el-button v-else type="primary" text bg
                >{{ pwdData.count }}s后重试</el-button
              >
            </div>
          </el-form>
        </el-row>
        <el-row class="buttonRow">
          <el-button type="primary" @click="editPassowrd">修改</el-button>
          <el-button type="info" @click="pwdReset">重置</el-button>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="注销账号">
        <el-row class="logOutFormrow">
          <el-form
            ref="logOutFormRef"
            :rules="logOutRules"
            :model="logOutForm"
            label-width="auto"
            label-position="left"
            status-icon
          >
            <el-form-item label="邮箱:" prop="email">
              <el-input placeholder="请输入邮箱" v-model="logOutForm.email" />
            </el-form-item>
            <el-form-item label="密码:" prop="pwd">
              <el-input
                placeholder="请输入密码"
                v-model="logOutForm.pwd"
                show-password
              />
            </el-form-item>
            <div class="codeRow">
              <el-form-item label="验证码:" prop="code">
                <el-input
                  placeholder="请输入邮箱验证码"
                  v-model="logOutForm.code"
                />
              </el-form-item>
              <el-button
                v-if="logoutData.show"
                type="primary"
                @click="sendEmail"
                plain
              >
                获取验证码
              </el-button>
              <el-button v-else type="primary" text bg
                >{{ logoutData.count }}s后重试</el-button
              >
            </div>
          </el-form>
        </el-row>
        <el-row class="buttonRow">
          <el-button type="primary" @click="confirmLogOut">确认注销</el-button>
          <el-button type="info" @click="logOutReset">重置</el-button>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </el-row>
</template>

<style lang="less" scoped>
.UMwithEP-box {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: aliceblue;
  padding-bottom: 60px;

  .el-tabs {
    width: 75%;
    height: 100%;
    margin-top: 2%;

    .personalFormrow {
      display: flex;
      justify-content: center;
      width: auto;
      height: auto;
      margin-top: 2%;

      .el-form {
        width: 80%;

        .el-form-item {
          width: 45%;
        }

        .textarea {
          width: 95%;
        }
      }
    }

    // 修改密码
    .updateFormrow {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 2%;

      .el-form {
        width: 80%;

        .el-form-item {
          width: 50%;
        }

        .codeRow {
          width: 70%;
          display: flex;
          flex-direction: row;

          .el-button {
            margin-left: 10px;
            width: 115px;
          }
        }
      }
    }

    // 修改密码
    .logOutFormrow {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 2%;

      .el-form {
        width: 80%;

        .el-form-item {
          width: 50%;
        }

        .codeRow {
          width: 70%;
          display: flex;
          flex-direction: row;

          .el-button {
            margin-left: 10px;
            width: 115px;
          }
        }
      }
    }

    //修改密码按钮
    .buttonRow {
      width: 60%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 2%;
    }
  }
}
</style>

